import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  Image,
  ImageBackground,
  Dimensions,
  ScrollView,
  KeyboardAvoidingView
} from 'react-native';
import { Input, Button } from 'react-native-elements';
import Icon from 'react-native-vector-icons/FontAwesome';
import SendCodeButton from '../compenents/SendCodeButton';
const md5= ()=>{

};
const SCREEN_WIDTH = Dimensions.get('window').width;
const SCREEN_HEIGHT = Dimensions.get('window').height;

const BG_IMAGE = require('../assets/images/bg_screen1.jpg');

export default class LoginScreen1 extends Component {
  constructor(props) {
    super(props);

    this.state = {
      fontLoaded: true,
      phone_valid: true,
      password: '',
      login_failed: false,
      showLoading: false,
      phone:'',
      code:'',
    };
  }


  validateEmail(phone) {
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

    return re.test(phone);
  }

  sendCode = async (cb)=>{
    if(this.state.phone.length !=11){
      this.setState({phone_valid:false});
      return;
    }
    cb(false,true);
    try{
      let ctime=Date.parse(new Date())/1000;
      let randstr='';
      let sign=md5(md5(randstr+''+ctime).toString()+randstr).toString();
      let param=`ctime=${ctime}&randstr=${randstr}&sign=${sign}&phone=${this.state.phone}&type=1`;
      //console.log(param);
      let response = await fetch('http://viquan.droyee.com/Login/Register/send_code?'+param);
      let responseJson = await response.json();
      //console.log(responseJson);
      if(responseJson.status==0){
        cb(true);
      }else{
        cb(false,false);
        alert(responseJson.msg);
      }
      
    }catch(err){
      console.log(err);
      cb(false,false);
      alert('发送失败');
    }
  }
  doReg = async ()=>{
    if(this.state.phone.length !=11){
      this.setState({phone_valid:false});
      return;
    }
    if(this.state.password.length <6){
        alert('请设置密码');
      return;
    }
    if(this.state.code.length !=6){
        alert('请输入验证码');
      return;
    }
    let param=`phone=${this.state.phone}&password=${this.state.password}&phonecode=${this.state.code}&token=@viquan168!`;

    try{
      let response = await fetch('http://viquan.droyee.com/Login/Register/reg?'+param);
      let responseJson = await response.json();
      console.log(responseJson);
      if(responseJson.status==1){
        alert('注册成功,请去登录');
      }else{
        alert(responseJson.msg);
      }
    }
    catch(err){
      console.log(err);
      alert('操作失败');
    }
  }
  render() {
    const { phone,code, password, phone_valid, showLoading, } = this.state;

    return (
        <ScrollView scrollEnabled={false} keyboardShouldPersistTaps="handled" contentContainerStyle={styles.container}>
        
        <ImageBackground source={BG_IMAGE} style={styles.bgImage}>
          {this.state.fontLoaded ? (
            <View style={styles.loginView}>

              <View style={styles.loginInput}>
              <Input
                  leftIcon={
                    <Icon
                      name="phone"
                      color="white"
                      size={25}
                    />
                  }
                  containerStyle={{ marginVertical: 10 }}
                  onChangeText={phone => this.setState({ phone,phone_valid:true })}
                  value={phone}
                  inputStyle={{ marginLeft: 10, color: 'white' }}
                  keyboardAppearance="light"
                  placeholder="手机号"
                  autoFocus={false}
                  autoCapitalize="none"
                  autoCorrect={false}
                  keyboardType="phone-pad"
                  blurOnSubmit={false}
                  placeholderTextColor="white"
                  errorStyle={{ textAlign: 'center', fontSize: 12 }}
                  errorMessage={
                    phone_valid ? null : '请输入正确的手机号'
                  }
                  style={{borderColor:'red',borderWidth:2}}
                />

                <Input
                  leftIcon={
                    <Icon
                      name="circle-o"
                      color="white"
                      size={25}
                    />
                  }
                  rightIcon={
                    <SendCodeButton onPress={this.sendCode}/>
                  }
                  containerStyle={{ marginVertical: 10 }}
                  onChangeText={code => this.setState({ code })}
                  value={code}
                  inputStyle={{ marginLeft: 10, color: 'white' }}
                  keyboardAppearance="light"
                  placeholder="验证码"
                  autoFocus={false}
                  autoCapitalize="none"
                  autoCorrect={false}
                  keyboardType="phone-pad"
                  blurOnSubmit={false}
                  placeholderTextColor="#eee"
                />

                <Input
                  leftIcon={
                    <Icon
                      name="lock"
                      color="white"
                      size={25}
                    />
                  }
                  containerStyle={{ marginVertical: 10 }}
                  onChangeText={password => this.setState({ password })}
                  value={password}
                  inputStyle={{ marginLeft: 10, color: 'white' }}
                  secureTextEntry={true}
                  keyboardAppearance="light"
                  placeholder="密码"
                  autoCapitalize="none"
                  autoCorrect={false}
                  keyboardType="default"
                  returnKeyType="done"
                  blurOnSubmit={true}
                  placeholderTextColor="white"
                />
              </View>

              
              <View style={styles.footerView}>

              <Button
                title="注册"
                activeOpacity={1}
                underlayColor="transparent"
                onPress={this.doReg}
                loading={showLoading}
                loadingProps={{ size: 'small', color: 'white' }}
                disabled={!phone_valid && password.length < 8}
                buttonStyle={{
                  height: 50,
                  width: 250,
                  backgroundColor: 'transparent',
                  borderWidth: 2,
                  borderColor: 'white',
                  borderRadius: 30,
                }}
                containerStyle={{ marginVertical: 10 }}
                titleStyle={{ fontWeight: 'bold', color: 'white' }}
              />

                <Text style={{ color: 'grey',marginTop:10 }}>已有账号?</Text>
                <Button
                  title="去登录"
                  type="clear"
                  activeOpacity={0.5}
                  titleStyle={{ color: 'white', fontSize: 15 }}
                  containerStyle={{ marginTop: -5 }}
                  onPress={() =>this.props.navigation.navigate('Login')}
                />
              </View>
            </View>
          ) : (
            <Text>Loading...</Text>
          )}
        </ImageBackground>
      </ScrollView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#293046',
    width: SCREEN_WIDTH,
    height: SCREEN_HEIGHT,
    alignItems: 'center',
    justifyContent: 'space-around',
  },
  formContainer: {
    flex: 1,
    justifyContent: 'space-around',
    alignItems: 'center',
  },
  bgImage: {
    flex: 1,
    top: 0,
    left: 0,
    width: SCREEN_WIDTH,
    height: SCREEN_HEIGHT,
    justifyContent: 'center',
    alignItems: 'center',
  },
  loginView: {
    marginTop: 10,
    backgroundColor: 'transparent',
    width: '80%',
    height: 400,
  },
  loginTitle: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  travelText: {
    color: 'white',
    fontSize: 30,
    fontFamily: 'bold',
  },
  plusText: {
    color: 'white',
    fontSize: 30,
    fontFamily: 'regular',
  },
  loginInput: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  footerView: {
    marginTop: 20,
    flex: 0.5,
    justifyContent: 'center',
    alignItems: 'center',
  },
});
